<?php


namespace App\Services\Home;

use App\Models\Banner;
use App\Models\BannerType;

class BannerService
{
    protected $banner;
    protected $banner_type;
    public function __construct(Banner $banner, BannerType $banner_type){
        $this->banner = $banner;
        $this->banner_type = $banner_type;
    }

    /**
     * 获取幻灯列表（后端分页）
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBanner($params = []){
        $take = $params['pageSize']?:10;
        $skip = (($params['page']?:1) - 1) * $take;
        $banners = $this->banner::skip($skip)
            ->take($take)
            ->orderBy('order_no','asc')
            ->get();
        foreach ($banners as $banner){
            $banner->image_mb = $banner->image_mb?[$banner->image_mb]:null;
            $banner->image_pc = $banner->image_pc?[$banner->image_pc]:null;
        }
        return Success('获取成功！',$banners);
    }

    /**
     * 获取幻灯列表（前端）
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBannerList(){
        $banners = $this->banner_type::with('banners')->get();
        return Success('获取成功！',$banners);
    }

    /**
     * 更新/添加幻灯
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrUpdateBanner($params){
        if (isset($params['id'])){
            $menu = Banner::find($params['id']);
        }else{
            $menu = new Banner();
        }
        unset($params['id']);
        if (isset($params['image_url'])){
            $params['image_url'] = $params['image_url'][0];
        }

        foreach ($params as $k => $v){
            $menu->$k = $v;
        }
        if ($menu->save()){
            return Success('操作成功！', $params);
        }else{
            return Error('操作失败！');
        }
    }
}
